import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import java.util.Random;

@Aspect
public class OrderAspect {
    private Random random = new Random();

    // 1. 前置增强：对add, delete, find方法
    @Before("execution(* OrderService.add(..)) || execution(* OrderService.delete(..)) || execution(* OrderService.find(..))")
    public void beforeAdvice() {
        System.out.println("hello, 我是一个前置增强");
    }

    // 2. 后置增强：对add, delete方法
    @AfterReturning("execution(* OrderService.add(..)) || execution(* OrderService.delete(..))")
    public void afterAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    // 3. 获取方法返回值并输出
    @AfterReturning(pointcut = "execution(* OrderService.*(..))", returning = "result")
    public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        if (result != null) {
            System.out.println(methodName + "方法的返回值: " + result);
        } else {
            System.out.println(methodName + "方法没有返回值");
        }
    }

    // 4. 计算方法执行时间
    @Around("execution(* OrderService.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed(); // 执行目标方法
        long endTime = System.currentTimeMillis();
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName + "方法执行时间: " + (endTime - startTime) + "毫秒");
        return result;
    }

    // 5. 权限校验增强：对add, delete方法
    @Before("execution(* OrderService.add(..)) || execution(* OrderService.delete(..))")
    public void permissionCheck(JoinPoint joinPoint) throws Throwable {
        int permission = random.nextInt(2); // 生成0或1的随机数
        String methodName = joinPoint.getSignature().getName();

        if (permission == 0) {
            System.out.println("权限校验通过，允许执行" + methodName + "方法");
        } else {
            System.out.println("权限校验失败，禁止执行" + methodName + "方法");
            // 如果没有权限，抛出异常终止方法执行
            throw new RuntimeException("没有执行" + methodName + "方法的权限");
        }
    }
}
    